from flask import current_app, jsonify
from flask import render_template
from flask import request

from business.models import ProductNews
from business.modules.quest_product import quest_product_blu
from business.utils.response_code import RET


@quest_product_blu.route('/product_news')
def product_news():
    """
    探秘产品数据
    :return:
    """

    # 1. 获取参数
    # 产品新闻的分类id
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2. 校验参数
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = []
    filters.append(ProductNews.category_id == cid)

    # 3. 查询数据
    try:
        paginate = ProductNews.query.filter(*filters).order_by(ProductNews.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 取到当前页的数据
    productnews_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    productnews_dict_li = []
    for productnews in productnews_model_list:
        productnews_dict_li.append(productnews.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "productnews_dict_li": productnews_dict_li
    }

    return render_template('front/Quest Product.html', data=data)